package com.vast.admin.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.google.gson.Gson;
import com.vast.admin.api.CietacApi;
import com.vast.admin.api.cietac.entity.*;
import com.vast.admin.entity.ArbitrationCase;
import com.vast.admin.entity.Contract;
import com.vast.admin.entity.dto.ArbitrationCaseDTO;
import com.vast.admin.entity.dto.RespondentDTO;
import com.vast.admin.mapper.ArbitrationCaseMapper;
import com.vast.common.core.domain.Result;
import com.vast.common.core.domain.entity.SysRole;
import com.vast.common.core.domain.entity.SysUser;
import com.vast.system.exception.BusinessException;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Base64Utils;
import org.springframework.web.multipart.MultipartFile;
import sun.misc.BASE64Encoder;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.*;

@Slf4j
@Service
public class ArbitrationCaseService extends ServiceImpl<ArbitrationCaseMapper, ArbitrationCase> {

	@Autowired
	private ContractService contractService;

	@Autowired
	private CietacApi cietacApi;

	/**
	 * 分页查询
	 * @param page
	 * @param arbitrationCase
	 * @param manager
	 * @return
	 */
	public IPage<ArbitrationCase> page(Page<ArbitrationCase> page, ArbitrationCase arbitrationCase, SysUser manager) {
		QueryWrapper<ArbitrationCase> arbitrationCaseQueryWrapper = new QueryWrapper<>();
		arbitrationCaseQueryWrapper.like(StringUtils.isNotBlank(arbitrationCase.getContractName()),
			ArbitrationCase.COL_CONTRACT_NAME, arbitrationCase.getContractName())
			.eq(StringUtils.isNotBlank(arbitrationCase.getContractName()), ArbitrationCase.COL_CONTRACT_NO, arbitrationCase.getContractNo());
		List<SysRole> roles = manager.getRoles();
		boolean isAdmin = false;
		for (SysRole role : roles) {
			if (role.getRoleKey().equals("admin")) {
				isAdmin = true;
				break;
			}
		}
		if (!isAdmin) {
			arbitrationCaseQueryWrapper.eq(ArbitrationCase.COL_CREATE_BY, manager.getUserId());
		}
		arbitrationCaseQueryWrapper.orderByDesc(ArbitrationCase.COL_CREATE_TIME);
		return super.page(page, arbitrationCaseQueryWrapper);
	}

	/**
	 * 保存案件信息
	 * @param arbitrationCaseStr
	 * @param files
	 * @param manager
	 * @return
	 */
	@Transactional(rollbackFor = Exception.class)
	public Result<CietacLawcaseId> saveArbitrationCase(String arbitrationCaseStr, MultipartFile[] files, SysUser manager) {
		Gson gson = new Gson();
		ArbitrationCaseDTO arbitrationCaseDTO = gson.fromJson(arbitrationCaseStr, ArbitrationCaseDTO.class);
		Long contractId = arbitrationCaseDTO.getContractId();
		if (contractId == null) {
			throw new BusinessException("合同ID缺失");
		}
		Contract contract = contractService.getById(contractId);
		if (contract == null) {
			throw new BusinessException("未找到合同");
		}
		byte[][] contractPdfs = contractService.downloadContract(contractId);
		arbitrationCaseDTO.setContractName(contract.getContractName());
		arbitrationCaseDTO.setContractNo(contract.getContractNo());
		arbitrationCaseDTO.setContractSignTime(new SimpleDateFormat("yyyy-MM-dd").format(contract.getCreateTime()));
		//合同附件
//        arbitrationCaseDTO.getContractAttachment(contract.getContractName() + ".pdf");
		BASE64Encoder encode = new BASE64Encoder();
		arbitrationCaseDTO.setContractAttachment(new Attachment(contract.getContractName() + ".pdf", "data:application/pdf;" + encode.encode(contractPdfs[0])));
		Evidence[] evidences = new Evidence[arbitrationCaseDTO.getEvidences().length + contractPdfs.length - 1];
		try {

			//上传附件处理
			Map<String, MultipartFile> fileMap = new HashMap<>();
			for (MultipartFile multipartFile : files) {
				fileMap.put(multipartFile.getOriginalFilename(), multipartFile);
			}

			//被申请人附件
			for (RespondentDTO respondent : arbitrationCaseDTO.getRespondents()) {
				if ("1".equals(respondent.getType())) {
					//个人
					multipartFile2Attachment(fileMap, respondent.getIdNumberFront());
					multipartFile2Attachment(fileMap, respondent.getIdNumberOpposite());
				} else if ("2".equals(respondent.getType())) {
					//企业
					multipartFile2Attachment(fileMap, respondent.getCorporateIdNumberFront());
					multipartFile2Attachment(fileMap, respondent.getCorporateIdNumberOpposite());
					multipartFile2Attachment(fileMap, respondent.getCorporateCertification());
					multipartFile2Attachment(fileMap, respondent.getBusinessLicensePhoto());
				}

			}

			int evidenceIndex = 0;
			//证据附件
			for (Evidence evidence : arbitrationCaseDTO.getEvidences()) {
				multipartFile2Attachment(fileMap, evidence.getEvidenceAttachment());
				evidences[evidenceIndex] = evidence;
				evidenceIndex ++;
			}

			for (int i = 1; i < contractPdfs.length; i ++) {
				String contractAttachmentName = contract.getContractName() + i;
				Attachment attachment = new Attachment(contractAttachmentName + ".pdf", "data:application/pdf;" + encode.encode(contractPdfs[i]));
				Evidence evidence = new Evidence();
				evidence.setEvidenceName(contractAttachmentName);
				evidence.setEvidenceRemark("合同原件");
				evidence.setEvidenceAttachment(attachment);
				evidences[arbitrationCaseDTO.getEvidences().length + i - 1] = evidence;
			}

		} catch (IOException e) {
			log.error("上传附件处理失败", e);
			throw new BusinessException("上传附件处理失败");
		}
		ArbitrationCase arbitrationCase = new ArbitrationCase();
		BeanUtils.copyProperties(arbitrationCaseDTO, arbitrationCase);
		SubmitCase submitCase = new SubmitCase();
		BeanUtils.copyProperties(arbitrationCaseDTO, submitCase);
		Respondent[] respondents = new Respondent[arbitrationCaseDTO.getRespondents().length];
		for (int i = 0; i < arbitrationCaseDTO.getRespondents().length; i ++) {
			respondents[i] = arbitrationCaseDTO.getRespondents()[i].transfer();
		}
		submitCase.setRespondents(respondents);
		submitCase.setEvidences(evidences);
		Result<CietacLawcaseId> result = cietacApi.submitCase(manager.getMobile(), submitCase);
		if (result.getCode() != 0) {
			throw new BusinessException(result.getMsg());
		}
		arbitrationCase.setCaseId(result.getData().getLawcaseId());
		arbitrationCase.setAmount(arbitrationCaseDTO.getAmount().doubleValue());
		arbitrationCase.setCompanyId(manager.getCompanyId());
		arbitrationCase.setCreateBy(manager.getUserId());
		arbitrationCase.setCreateTime(new Date());
		arbitrationCase.setStatus("5");
		super.save(arbitrationCase);
		Result<Void> r = cietacApi.startHandleCase(manager.getMobile(), new StartHandleCase(arbitrationCase.getCaseId(),
			arbitrationCaseDTO.getArbitrationRequest(), arbitrationCaseDTO.getArbitrationBasis(), arbitrationCaseDTO.getArbitrationReason()));
		if (r.getCode() != 0) {
			throw new BusinessException(r.getMsg());
		}
		return result;
	}

	/**
	 * 文件转base64
	 * @param fileMap
	 * @param attachment
	 * @throws IOException
	 */
	private void multipartFile2Attachment(Map<String, MultipartFile> fileMap, Attachment attachment) throws IOException {
		if (attachment != null) {
			MultipartFile file = fileMap.get(attachment.getFileName());
			attachment.setFileName(attachment.getFileName().substring(attachment.getFileName().indexOf("|") + 1));
			attachment.setBase64("data:image/" + attachment.getFileName().substring(attachment.getFileName().lastIndexOf(".") + 1) + ";" + Base64Utils.encodeToString(file.getBytes()));
		}
	}

	/**
	 * 同步案件状态
	 */
	@Transactional(rollbackFor = Exception.class)
	public void syncStatus() {
		QueryWrapper<ArbitrationCase> arbitrationCaseQueryWrapper = new QueryWrapper<>();
		//项目状态 45已过期 46已关闭 不再同步
		arbitrationCaseQueryWrapper.notIn(ArbitrationCase.COL_STATUS, "45", "46");
		List<ArbitrationCase> arbitrationCases = super.list(arbitrationCaseQueryWrapper);
		if (arbitrationCases != null && !arbitrationCases.isEmpty()) {
			List<Long> projectIds = new ArrayList<>(arbitrationCases.size());
			arbitrationCases.forEach(arbitrationCase -> projectIds.add(arbitrationCase.getCaseId()));
			Result<List<ArbitrationCase>> caseStatusResult = cietacApi.caseStatus(projectIds);
			if (caseStatusResult.getCode() == 0) {
				for (ArbitrationCase arbitrationCase : caseStatusResult.getData()) {
					UpdateWrapper<ArbitrationCase> arbitrationCaseUpdateWrapper = new UpdateWrapper<>();
					arbitrationCaseUpdateWrapper.set(ArbitrationCase.COL_STATUS, arbitrationCase.getStatus())
						.eq(ArbitrationCase.COL_CASE_ID, arbitrationCase.getCaseId());
					super.update(arbitrationCaseUpdateWrapper);
				}
			} else {
				log.error("案件状态同步失败");
			}
		}
	}

}

